<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\RowActions\ActiveInfoAction;
use App\Admin\Actions\Grid\RowActions\AgreementAuditAction;
use App\Admin\Actions\Grid\RowActions\AgreementStopAction;
use App\Admin\Actions\Grid\RowActions\AuditAction;
use App\Admin\Actions\Grid\RowActions\AuditPayStatusAction;
use App\Admin\Actions\Grid\RowActions\AuditRemarkAction;
use App\Admin\Actions\Grid\Tools\BatchAuditPayStatusTools;
use App\Admin\Actions\Grid\Tools\ExportAgreement;
use App\Admin\Repositories\AgreementRepository;
use App\Admin\Repositories\ProjectAgreement;
use App\Models\AdminUser;
use App\Models\ProjectAgreement as ModelsProjectAgreement;
use App\Models\User;
use App\Support\Data;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

/**
 * 协议管理
 *
 * Class AgreementManageController
 * @package App\Admin\Controllers
 */
class AgreementManageController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new AgreementRepository, function (Grid $grid) {
            // $grid->fixColumns(4, -1);
            // $grid->fixColumns(3, -1);
            // $grid->disablePerPages();
            // $grid->paginate(10);
            // $grid->disableBatchDelete();
            $grid->disableCreateButton();
            $grid->disableEditButton();
            $grid->disableViewButton();
            $grid->disableDeleteButton();

            $grid->showColumnSelector();

            if (!Admin::user()->can('batch-delete-agreement')) {
                // $grid->disableRowSelector();
                $grid->disableBatchDelete();
            }

            // 判断是否有批量允许支付
            if (Admin::user()->can('batch-audit-pay-status')) {
                $grid->tools([
                    new BatchAuditPayStatusTools(),
                    // new UploadReceiptFormBatchTools(),
                ]);
            }

            // // 设置禁止选中行
            // $grid->rowSelector()->disable(function ($row) {
            //     // dump(($row->audit_first != 1 || $row->pay_status == 0));
            //     if ($row->audit_first == 1) {
            //         if ($row->pay_status == 0) {

            //             return false;
            //         } else {
            //             return true;
            //         }
            //     } else {
            //         return true;
            //     }
            // });

            $grid->scrollbarX();
            $grid->withBorder();
            $grid->addTableClass(['table-text-center']);

            // $grid->batchActions([new ExportAgreement()]);
            if (Admin::user()->can('export-data')) {
                $grid->tools([
                    new ExportAgreement('导出数据'),
                ]);
            }
            $grid->column('id');
            $grid->column('project_name');
            $grid->column('project_sn');
            $grid->column('company_short');
            $grid->column('agreement_code');
            $grid->column('user_auth_name');

            $grid->column('税前金额')->display(function () {
                list($tax, $beforeTaxAmount) = Data::getTaxRate($this->fee_type_value);
                return $beforeTaxAmount;
            });
            $grid->column('纳税金额')->display(function () {
                list($tax, $beforeTaxAmount) = Data::getTaxRate($this->fee_type_value);
                return $tax;
            });
            $grid->column('fee_type_value', '税后金额')->display(function () {
                return number_format($this->fee_type_value, 2, '.', '');
            });
            // $grid->column('agreement_file');
            $grid->column('agreement_file', '协议文件')->display(function ($url) {
                return '<a href="' . $url . '" target="_blank"><i class="fa fa-download"></i> 协议文件</a>';
            });
            $grid->column('agreement_file_sign')->display(function ($pictures) {
                return explode(',', $pictures);
            })->image('', 100, 100);;
            // $grid->column('agreement_file_sign', '签字文件')->display(function ($url) {
            //     if (empty($url)) {
            //         return ' - ';
            //     } else {
            //         return '<a href="' . $url . '" target="_blank"><i class="fa fa-download"></i> 签字文件</a>';
            //     }
            // });
            $grid->column('快递单号')->display(function () {
                if (empty($this->express_name) && empty($this->express_code)) {
                    return ' - ';
                } else {
                    return $this->express_name . '<br>' . $this->express_code;
                }
            });
            $grid->column('audit_first', '协议审核状态')
                ->using(ProjectAgreement::getAuditStatus('audit_first'))
                ->label([1 => 'success', '-1' => 'danger']);
            $grid->column('pay_status', '支付状态')
                ->using([0 => '待审核', 1 => '允许支付', 2 => '已支付', -1 => '已驳回'])
                ->label([
                    0 => 'primary',
                    -1 => 'danger',
                    2 => 'success',
                    1 => Admin::color()->info(),
                ]);
            $grid->column('paymentd_at', '支付时间')->display(function ($paymentd_at) {
                if (empty($paymentd_at)) {
                    return ' - ';
                } else {
                    return $paymentd_at;
                }
            });
            $grid->column('audit_fee', '劳务审核状态')
                ->using(ProjectAgreement::getAuditStatus('audit_fee'))
                ->label([1 => 'success', '-1' => 'danger']);

            $grid->column('receipt_form', '回执单')->display(function ($pictures) {
                return explode(',', $pictures);
            })->image('', 100, 100);
            // $grid->column('receipt_form', '回执单')->display(function ($url) {
            //     if (empty($url)) {
            //         return ' - ';
            //     } else {
            //         return '<a href="' . $url . '" target="_blank"><i class="fa fa-download"></i> 回执单</a>';
            //     }
            // });

            $grid->column('created_at');

            $grid->actions(function (Grid\Displayers\Actions $actions) {

                if (($this->audit_first == -1 || $this->audit_fee == -1) && Admin::user()->can('check-agreement-audit-view')) {
                    $actions->append(new AuditRemarkAction()); // 审核意见
                }

                // 审批流(1=协议审核,2=劳务审核)
                if ($this->audit_global_status == 1 && Admin::user()->can('agreement-audit') && $this->status <> -2) {
                    $actions->append(new AuditAction('协议审核'));
                }
                // 审批支付状态
                if ($this->pay_status == 0 && Admin::user()->can('audit-pay-status') && $this->status == 1) {
                    $actions->append(new AuditPayStatusAction('支付审核'));
                }

                if (Admin::user()->can('agreement-audit-info')) {
                    $actions->append(new AgreementAuditAction()); // 审核信息
                }

                if (Admin::user()->can('activity-info')) {
                    $actions->append(new ActiveInfoAction()); // 活动信息
                }

                if ($this->status != -2) { // || Admin::user()->can('agreement-termination')
                    if (Admin::user()->isAdministrator()) {
                        $actions->append(new AgreementStopAction()); // 中止
                    }
                }
            });

            $grid->filter(function (Grid\Filter $filter) {

                $filter->equal('project_sn');
                $filter->equal('agreement_code');
                $filter->like('active_name');
                $filter->between('active_date', '会议日期')->date();
                $filter->between('active_time', '会议时间')->time();
                $where = [];
                $currLoginUser = Admin::user();
                if ($currLoginUser->company_id != null) {
                    $where = ['company_id' => $currLoginUser->company_id];
                }
                // $project = \App\Models\Project::where($where)->select('id', 'project_name')->pluck('project_name', 'id');
                $project = \App\Models\Project::where($where)->select('id', 'project_name')->get();

                foreach ($project as $key => $val) {
                    $agreementCount = ModelsProjectAgreement::where(['project_id' => $val['id'], 'status' => 1])->count();

                    // dump($val['id']);
                    $val['project_name'] = $val['project_name'] . ' / 协议数量：' . $agreementCount;
                }
                // dd($project->pluck('project_name', 'id'));
                $filter->equal('project_id', '所属项目')
                    ->select($project->pluck('project_name', 'id'));
                $filter->equal('pay_status')->select(ProjectAgreement::getPayStatus());
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new ProjectAgreement(), function (Show $show) {
            $show->field('id');
            $show->field('project_id');
            $show->field('user_id');
            $show->field('agreement_code');
            $show->field('user_auth_name');
            $show->field('bank_card');
            $show->field('bank_username');
            $show->field('bank_name');
            $show->field('bank_addr');
            $show->field('id_card');
            $show->field('mobile');
            $show->field('company');
            $show->field('fee_type_key');
            $show->field('fee_type_value');
            $show->field('role');
            $show->field('active_date');
            $show->field('active_week');
            $show->field('active_time_begin');
            $show->field('active_time_end');
            $show->field('express_name');
            $show->field('express_code');
            $show->field('status');
            $show->field('pay_status');
            $show->field('audit_global_status');
            $show->field('audit_remark');
            $show->field('audit_fee');
            $show->field('audit_first');
            $show->field('audit_second');
            $show->field('audit_final');
            $show->field('audit_log');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ProjectAgreement(), function (Form $form) {
            $form->display('id');
            $form->text('project_id');
            $form->text('user_id');
            $form->text('agreement_code');
            $form->text('user_auth_name');
            $form->text('bank_card');
            $form->text('bank_username');
            $form->text('bank_name');
            $form->text('bank_addr');
            $form->text('id_card');
            $form->text('mobile');
            $form->text('company');
            $form->text('fee_type_key');
            $form->text('fee_type_value');
            $form->text('role');
            $form->text('active_date');
            $form->text('active_week');
            $form->text('active_time_begin');
            $form->text('active_time_end');
            $form->text('express_name');
            $form->text('express_code');
            $form->text('status');
            $form->text('pay_status');
            $form->text('audit_global_status');
            $form->text('audit_remark');
            $form->text('audit_fee');
            $form->text('audit_first');
            $form->text('audit_second');
            $form->text('audit_final');
            $form->text('audit_log');

            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
